import { useState, useEffect } from "react";
import { useParams } from 'react-router-dom';

import Box from '@mui/material/Box';
import List from '@mui/material/List';
import Stack from '@mui/material/Stack';
import Button from '@mui/material/Button';
import ListItem from '@mui/material/ListItem';
import TextField from '@mui/material/TextField';
import Typography from '@mui/material/Typography';

import { useRouter } from 'src/routes/hooks';

import { isValidPort } from 'src/utils/valid';

// 模拟 API 数据
const mockProductData = {
    'e99f09a7-dd88-49d5-b1c8-1daf80c2d7b0': {
        serviceName: 'nginx-service',
        image: 'nginx:latest',
        containerName: 'nginx-container',
        restart: 'always',
        ports: ['80:80', '443:443'],
        volumes: ['./nginx/conf:/etc/nginx/conf.d', './nginx/html:/usr/share/nginx/html'],
        environment: ['NGINX_HOST=localhost', 'NGINX_PORT=80'],
        networks: 'frontend',
        depends_on: 'db'
    },
    'e99f09a7-dd88-49d5-b1c8-1daf80c2d7b6': {
        serviceName: 'pay-service',
        image: 'pay:8.0',
        containerName: 'pay-container',
        restart: 'always',
        ports: ['8080:8080'],
        volumes: ['./pay/data:/var/lib/pay'],
        environment: ['NGINX_HOST=localhost', 'NGINX_PORT=80'],
        networks: 'backend',
        depends_on: ''
    }
};

export default function ProductInstallView() {
    const { id } = useParams();
    const router = useRouter();
    const [formData, setFormData] = useState({
        serviceName: '',
        image: '',
        containerName: '',
        restart: 'always',
        ports: [] as string[],
        volumes: [] as string[],
        environment: [] as string[],
        networks: '',
        depends_on: '',
    });

    useEffect(() => {
        // 模拟 API 调用
        const mockFetchData = () => {
            const productData = mockProductData[id as keyof typeof mockProductData];
            if (productData) {
                setFormData(productData);
            }
        };

        mockFetchData();
    }, [id]);



    const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const { name, value } = e.target;
        setFormData((prev) => ({ ...prev, [name]: value }));
    };


    // 处理列表项的更新
    const handleListItemChange = (type: 'ports' | 'volumes' | 'environment', index: number, value: string) => {
        if (type === 'ports') {
            // 验证端口是否为正整数
            if (value === '' || isValidPort(value)) {
                const [_, containerPort] = formData.ports[index].split(':');
                setFormData(prev => ({
                    ...prev,
                    ports: prev.ports.map((item, i) => i === index ? `${value}:${containerPort}` : item)
                }));
            }
        } else if (type === 'volumes') {
            const [_, containerPath] = formData.volumes[index].split(':');
            setFormData(prev => ({
                ...prev,
                volumes: prev.volumes.map((item, i) => i === index ? `${value}:${containerPath}` : item)
            }));
        } else {
            setFormData(prev => ({
                ...prev,
                [type]: prev[type].map((item, i) => i === index ? value : item)
            }));
        }
    };

    const handleSubmit = () => {
        console.log('安装表单数据:', formData);
        router.push('/products');
    };

    return (
        <Box sx={{ maxWidth: 800, mx: 'auto', mt: 5, px: 3 }}>
            <Typography variant="h4" gutterBottom>
                安装项目
            </Typography>

            <form onSubmit={(e) => e.preventDefault()}>
                <Stack spacing={3}>
                    <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
                        <TextField
                            fullWidth
                            label="服务名称"
                            name="serviceName"
                            value={formData.serviceName}
                            onChange={handleChange}
                            required
                        />
                        <TextField
                            fullWidth
                            label="容器名称"
                            name="containerName"
                            value={formData.containerName}
                            onChange={handleChange}
                        />
                    </Stack>

                    <TextField
                        fullWidth
                        label="镜像"
                        name="image"
                        value={formData.image}
                        onChange={handleChange}
                        required
                    />

                    {/* 端口映射 */}
                    <Box>
                        <Typography variant="subtitle1" gutterBottom>端口映射</Typography>
                        <List>
                            {formData.ports.map((port, index) => {
                                const [hostPort, containerPort] = port.split(':');
                                return (
                                    <ListItem key={index}>
                                        <Stack direction="row" spacing={1} sx={{ width: '100%' }}>
                                            <TextField
                                                sx={{ flex: 1 }}
                                                value={hostPort}
                                                onChange={(e) => handleListItemChange('ports', index, e.target.value)}
                                                placeholder="主机端口"
                                                type="number"
                                                inputProps={{
                                                    min: 1,
                                                    max: 65535,
                                                    step: 1
                                                }}
                                                error={hostPort !== '' && !isValidPort(hostPort)}
                                                helperText={hostPort !== '' && !isValidPort(hostPort) ? "请输入1-65535之间的整数" : ""}
                                            />
                                            <Typography sx={{ py: 2 }}>:</Typography>
                                            <TextField
                                                sx={{ flex: 1 }}
                                                value={containerPort}
                                                disabled
                                                placeholder="容器端口"
                                            />
                                        </Stack>
                                    </ListItem>
                                );
                            })}
                        </List>
                    </Box>

                    {/* 卷映射 */}
                    <Box>
                        <Typography variant="subtitle1" gutterBottom>卷映射</Typography>
                        <List>
                            {formData.volumes.map((volume, index) => {
                                const [hostPath, containerPath] = volume.split(':');
                                return (
                                    <ListItem key={index}>
                                        <Stack direction="row" spacing={1} sx={{ width: '100%' }}>
                                            <TextField
                                                sx={{ flex: 1 }}
                                                value={hostPath}
                                                onChange={(e) => handleListItemChange('volumes', index, e.target.value)}
                                                placeholder="主机目录"
                                            />
                                            <Typography sx={{ py: 2 }}>:</Typography>
                                            <TextField
                                                sx={{ flex: 1 }}
                                                value={containerPath}
                                                disabled
                                                placeholder="容器目录"
                                            />
                                        </Stack>
                                    </ListItem>
                                );
                            })}
                        </List>
                    </Box>

                    {/* 环境变量 */}
                    <Box>
                        <Typography variant="subtitle1" gutterBottom>环境变量</Typography>
                        <List>
                            {formData.environment.map((env, index) => (
                                <ListItem key={index}>
                                    <TextField
                                        fullWidth
                                        value={env}
                                        onChange={(e) => handleListItemChange('environment', index, e.target.value)}
                                        placeholder="例如: MYSQL_ROOT_PASSWORD=123456"
                                    />
                                </ListItem>
                            ))}
                        </List>
                    </Box>

                    <Button
                        fullWidth
                        size="large"
                        variant="contained"
                        color="primary"
                        onClick={handleSubmit}
                    >
                        提交安装
                    </Button>
                </Stack>
            </form>
        </Box>
    );
}
